% M1 analysis

avg_act_po=[];
for ind=1:3
    for knd=1:5
        tmp=md(ind).rd(2*knd).act;
        tmp(tmp<2)=1;
        avg_act_po(ind,knd)=mean(mean(tmp));
    end
end


avg_act_pi=[];
for ind=1:3
    for knd=1:5
        tmp=md(ind).rd(2*knd-1).act;

        tmp(tmp<2)=1;
                figure;imagesc(tmp)
        avg_act_pi(ind,knd)=mean(mean(tmp));
    end
end


figure;hold on;
plot(avg_act_po','k')
plot(mean(avg_act_po),'k','linewidth',3)

plot(avg_act_pi','r--')
plot(mean(avg_act_pi),'r--','linewidth',3)






siteid=2;
tp=10;
aa=md(siteid).rd(tp).act;
aa(aa<1.5)=1;
first_act=[];
for ind=1:size(aa,1)
    tmp=find(aa(ind,3300:end)>1,1,'first');
    if ~isempty(tmp)
        first_act(ind)=tmp;
    else
        first_act(ind)=size(aa,2);
    end
end
[~,sort_id]=sort(first_act);
figure;imagesc(aa(sort_id,:))
figure;plot(md(siteid).rd(tp).velM_smoothed)

for ind = 1:32
    aa(:,ind)=ROIs(ind).activity;
end

% convert timing of aux_data on frame times of scanner

frame_times=get_frame_times(aux_data(2,:));
ft_index=1:length(frame_times);
aux_data=aux_data(:,frame_times(ft_index));

% corr coef sorting according to forward movement

for ind = 1:32
    tmp=corrcoef(ROIs(ind).activity, velFW);
    ccc(1,ind)=abs(tmp(1,2));
end

[~,sort_id] = sort(ccc)
figure, imagesc(aa(sort_id,:),clims)

velFW=diff(aux_data(5,:));
velFW(velFW>5)=velFW(velFW>5)-10;
velFW(velFW<-5)=velFW(velFW<-5)+10;
velM_raw=velFW;
velFW=ftfil(velFW,1000,0,10);

velR=diff(aux_data(8,:));
velR(velR>5)=velR(velR>5)-10;
velR(velR<-5)=velR(velR<-5)+10;
velM_raw=velR;
velR=ftfil(velR,1000,0,10);

% sorting according to PS

tmp2=find(abs(diff(round(aux_data(3,:)))>1))

bb=zeros
for knd = 1:32
    for ind = (tmp2(1)-100):(tmp2(1)+100)
        bb(knd,ind)=bb(knd,ind)+aa(knd,ind)
    end
end
mean_aa(knd,:)=bb(knd,:)/length(tmp2(1)-100:tmp2(1)+100)


  
for ind=1:32
    tmp=find(aa(ind,10:end)>200,1,'first');
    if ~isempty(tmp)
        first_act(ind)=tmp;
    else
        first_act(ind)=size(aa,2);
    end
end

[~,sort_id]=sort(first_act);
figure;imagesc(aa(sort_id,:))

run_t=find(diff(round(aux_data(4,:)))==);


